package com.kkb.interceptor;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

public class FileUploadInterceptor implements HandlerInterceptor {

    /**
     * 在文件上传之前判断文件后缀是否合法
     * @param request 请求
     * @param response 响应
     * @param handler 对象
     * @return 拦截成功/失败
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean flag = true;
        //判断是否是文件上传的请求
        if (request instanceof MultipartHttpServletRequest){
            MultipartHttpServletRequest upRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = upRequest.getFileMap();
            //遍历文件
            Iterator<String> iterator = fileMap.keySet().iterator();
            while (iterator.hasNext()){
                String key = iterator.next();
                MultipartFile file = upRequest.getFile(key);
                String fileName = file.getOriginalFilename();
                //取文件名的后缀
                String hz = fileName.substring(fileName.lastIndexOf("."));
                //判断后缀是否合法
                if (!hz.toLowerCase(Locale.ROOT).equals(".png") && !hz.toLowerCase(Locale.ROOT).equals(".jpg") && !hz.toLowerCase(Locale.ROOT).equals(".img")){

                    //不满足图片后缀，跳转到错误页面
                    request.getRequestDispatcher("/fileTypeError.jsp").forward(request,response);

                    flag = false;
                }
            }
        }

        return flag;
    }
}
